from haystack import tracing

from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.resources import Resource
from opentelemetry.semconv.resource import ResourceAttributes

# Service name is required for most backends
resource = Resource(attributes={
    ResourceAttributes.SERVICE_NAME: "haystack"  # Correct constant
})

tracer_provider = TracerProvider(resource=resource)
processor = BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces"))
tracer_provider.add_span_processor(processor)
trace.set_tracer_provider(tracer_provider)

# Tell Haystack to auto-detect the configured tracer
import haystack.tracing
haystack.tracing.auto_enable_tracing()

# Explicitly tell Haystack to use your tracer
from haystack.tracing import OpenTelemetryTracer

tracer = tracer_provider.get_tracer("my_application")
tracing.enable_tracing(OpenTelemetryTracer(tracer))